package com.v1.video.util.ali;

import android.content.Context;
import android.content.pm.PackageManager;
import com.alibaba.sdk.android.oss.OSSService;
import com.alibaba.sdk.android.oss.OSSServiceProvider;
import com.alibaba.sdk.android.oss.callback.SaveCallback;
import com.alibaba.sdk.android.oss.model.AccessControlList;
import com.alibaba.sdk.android.oss.model.AuthenticationType;
import com.alibaba.sdk.android.oss.model.ClientConfiguration;
import com.alibaba.sdk.android.oss.model.OSSException;
import com.alibaba.sdk.android.oss.model.TokenGenerator;
import com.alibaba.sdk.android.oss.storage.OSSFile;
import com.alibaba.sdk.android.oss.util.OSSLog;
import com.alibaba.sdk.android.oss.util.OSSToolKit;
import com.v1.video.domain.Header;
import com.v1.video.domain.UploadInfo;
import com.v1.video.option.db.PersonalCenterUploadDB;
import com.v1.video.util.AESHelper;
import com.v1.video.util.Logger;

/**
 * Created by zhouzhuo on 9/13/15.
 */
public class OSSAndroidDemo {
	private final String TAG = "OSSAndroidDemo";
    static String accessKey;
    static String screctKey;
    static String bucketName;

    public static String srcFileDir;
    public static OSSService ossService;
    private String uploadFileName = "v1video";
	/** 视频相关信息 */
	private Header header;	
	Context context = null;
	String key = "v1videoqiye.cn";
    public void main(Context context,Header header) {

        // 测试代码没有考虑AK/SK的安全性，保存在本地
        try {
            String accessKey1 = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getString("com.alibaba.app.ossak");
            String screctKey1 = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getString("com.alibaba.app.osssk");
            String bucketName1 = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getString("com.alibaba.app.ossbucketname");
            accessKey = AESHelper.decrypt(accessKey1,key); 
            screctKey = AESHelper.decrypt(screctKey1,key); 
            bucketName = AESHelper.decrypt(bucketName1,key); 
            Logger.i(TAG, "accessKey=="+accessKey);
            Logger.i(TAG, "screctKey=="+screctKey);
            Logger.i(TAG, "bucketName=="+bucketName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e){
        	e.printStackTrace();
        }

        // 在本地文件系统建立两个随机文件，用于后续的上传
        this.context = context;
        srcFileDir = header.filePath;
        this.uploadFileName = header.related_Video_Id;
        this.header = header;
        Logger.i(TAG, "文件路径srcFileDir="+srcFileDir);
//        try {
//            initLocalFile();
//        } catch (Exception ignore) {
//        }

        // 初始化ossService
        initOssService(context);

        runDemo();
    }

    private void initOssService(Context context) {
        // 开启Log
        OSSLog.enableLog();
        ossService = OSSServiceProvider.getService();

        ossService.setApplicationContext(context);//oss-cn-hangzhou.aliyuncs.com//v1oss.oss-cn-hangzhou.aliyuncs.com
        ossService.setGlobalDefaultHostId("oss-cn-hangzhou.aliyuncs.com"); // 设置region host 即 endpoint
        ossService.setGlobalDefaultACL(AccessControlList.PRIVATE); // 默认为private
        ossService.setAuthenticationType(AuthenticationType.ORIGIN_AKSK); // 设置加签类型为原始AK/SK加签
        ossService.setGlobalDefaultTokenGenerator(new TokenGenerator() { // 设置全局默认加签器
            @Override
            public String generateToken(String httpMethod, String md5, String type, String date,
                                        String ossHeaders, String resource) {

                String content = httpMethod + "\n" + md5 + "\n" + type + "\n" + date + "\n" + ossHeaders
                        + resource;

                return OSSToolKit.generateToken(accessKey, screctKey, content);
            }
        });
        ossService.setCustomStandardTimeWithEpochSec(System.currentTimeMillis() / 1000);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectTimeout(30 * 1000); // 设置全局网络连接超时时间，默认30s
        conf.setSocketTimeout(30 * 1000); // 设置全局socket超时时间，默认30s
        conf.setMaxConcurrentTaskNum(5); // 替换设置最大连接数接口，设置全局最大并发任务数，默认为6
        conf.setIsSecurityTunnelRequired(false); // 是否使用https，默认为false
        ossService.setClientConfiguration(conf);
    }

   

    public void runDemo() {

        // new Thread(new Runnable() {
        //     @Override
        //     public void run() {
        //         new ListObjectsInBucketDemo().show();
        //     }
        // }).start();

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                new GetAndUploadDataDemo().show();//ft_10.19
//            }
//        }).start();


         new Thread(new Runnable() {
             @Override
             public void run() {
            	 
//                 new GetAndUploadFileDemo().show();
            	 resumableUpload();
             }
         }).start();

        // new Thread(new Runnable() {
        //     @Override
        //     public void run() {
        //         new MultipartUploadDemo().show();
        //     }
        // }).start();
    }
    
    public void resumableUpload() {
        OSSFile bigfFile = ossService.getOssFile(ossService.getOssBucket(OSSAndroidDemo.bucketName), "mobile/"+uploadFileName+".mp4");
        try {
            bigfFile.setUploadFilePath(srcFileDir/* + "file10m.mp4"*/, "application/octet-stream");
            bigfFile.ResumableUploadInBackground(new SaveCallback() {

                @Override
                public void onSuccess(String objectKey) {
                    Logger.d(TAG, "[onSuccess] - " + objectKey + " upload success!");
                    header.state = "2";
                    PersonalCenterUploadDB.getInstance(context).updataUploadInfo(header,context);
                    UploadInfo.getInstance().setUploading(false);
                }

                @Override
                public void onProgress(String objectKey, int byteCount, int totalSize) {
                	Logger.d(TAG, "[onProgress] - current upload " + objectKey + " bytes: " + byteCount + " in total: " + totalSize);
                	UploadInfo.getInstance().setUploadedLength(byteCount);
//                    setUploadedLength(byteCount);
                }

                @Override
                public void onFailure(String objectKey, OSSException ossException) {
                	Logger.e(TAG, "[onFailure] - upload " + objectKey + " failed!\n" + ossException.toString());
                    ossException.printStackTrace();
                    ossException.getException().printStackTrace();
                    UploadInfo.getInstance().setUploading(false);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
